package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Comment struct {
	Id     uint   `json:"id"`
	PostId uint   `json:"post_id"`
	Text   string `json:"text"`
}

func main() {
	db, err := gorm.Open(mysql.Open("root:root@tcp(127.0.0.1:3306)/go_comments"), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	db.AutoMigrate(&Comment{})

	app := gin.Default()
	api := app.Group("/api")

	{
		api.GET("posts/:id/comments", func(c *gin.Context) {
			var comments []Comment
			db.Find(&comments, "post_id = ?", c.Param("id"))
			c.JSON(http.StatusOK, gin.H{"result": comments})
		})

		api.GET("/comments", func(c *gin.Context) {
			var comments []Comment
			db.Find(&comments)
			c.JSON(http.StatusOK, gin.H{"result": comments})
		})

		api.POST("/comments", func(c *gin.Context) {
			var comment Comment
			if err := c.ShouldBindJSON(&comment); err != nil {
				panic(err)
			} else {
				db.Create(&comment)

				body, err := json.Marshal(map[string]string{
					"text": comment.Text,
				})
				if err != nil {
					panic(err)
				}

				url := fmt.Sprintf("http://localhost:8000/api/posts/%d/comments", comment.PostId)
				_, err = http.Post(url, "application/json", bytes.NewBuffer(body))
				if err != nil {
					panic(err)
				}

				c.JSON(http.StatusCreated, gin.H{"result": comment})
			}
		})
	}

	app.Run(":8001")
}
